package net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class Receiver implements Runnable {
    private DatagramSocket receiver;
    private DatagramPacket packet;
    private String name;
    private int local;//本进程端口
    private static final int MAX_RECEIVE_BUFFER = 1024;
    public Receiver(int local,String targetName){
        this.local = local;
        this.name = targetName;
    }

    @Override
    //接收数据包
    public void run() {
        try {
            receiver = new DatagramSocket(local);//创建接收端
            while (true) {
                byte[] buf = new byte[1024*60];
                DatagramPacket data = new DatagramPacket(buf,0,buf.length);
                receiver.receive(data);//阻塞
                String input = new String(data.getData(),0,data.getLength());
                System.out.println(name+":"+input);
                if (input.equals("exit")||input.equals("bye")){
                    System.out.println("聊天结束");
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        receiver.close();
    }
}
